import type { RouteRecordRaw } from 'vue-router'
import breadcrumbs from './breadcrumbs'
import { getImportComponent } from '@/router/view'

export interface BreadcrumbItem {
  title: string
  icon: BusinessIconType
  name: string
  path: string
  menu: boolean
  view: string
  visible: boolean
  permission: string
  children: BreadcrumbItem[]
}

export type BreadcrumbSystemType = (typeof breadcrumbs)[number]['name']

export type BreadcrumbMenuType = { [K in BreadcrumbSystemType]: BreadcrumbItem[] }

export const getSystems = (): BreadcrumbItem[] => {
  return breadcrumbs.filter((breadcrumb) => breadcrumb.visible) as unknown as BreadcrumbItem[]
}

export const systems = getSystems()

export const getMenus = (permissions?: string[]): BreadcrumbMenuType => {
  const warp = (children: BreadcrumbItem[]): BreadcrumbItem[] => {
    return children
      .filter((c) => {
        if (c.menu && c.visible) {
          if (!permissions) {
            return true
          }
          return permissions.includes(c.permission)
        }
      })
      .map((c) => {
        const { children, ...props } = c
        return {
          ...props,
          children: children ? warp(children) : []
        }
      })
  }

  return (
    breadcrumbs
      // .filter((breadcrumb) => breadcrumb.visible && breadcrumb.children.length > 0)
      .reduce((acc, breadcrumb) => {
        acc[breadcrumb.name] = warp(breadcrumb.children as unknown as BreadcrumbItem[])
        return acc
      }, {} as BreadcrumbMenuType)
  )
}

// 所有菜单项
export const menus = getMenus()

export const getRoutes = (): RouteRecordRaw[] => {
  const warp = (
    children: BreadcrumbItem[],
    result: RouteRecordRaw[],
    breadcrumbs: string[] = []
  ): void => {
    children
      .filter((c) => c.visible)
      .forEach((c) => {
        const { children, name, path, view, ...props } = c
        const cBreadcrumbs = [...breadcrumbs, c.title]
        if (view) {
          result.push({
            name,
            path,
            component: getImportComponent(view),
            meta: {
              ...props,
              breadcrumbs: cBreadcrumbs
            }
          })
        }

        if (children.length > 0) {
          warp(children, result, cBreadcrumbs)
        }
      })
  }
  const result: RouteRecordRaw[] = []
  warp(breadcrumbs as unknown as BreadcrumbItem[], result)
  return result
}

export const routes = getRoutes()
